﻿using System;
using System.Windows;
using System.Windows.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SlXnaApp1.GameObjects
{
    public class TargetBtn
    {
        public class FinishEventArgs
        {
            public FinishEventArgs(int score) { Score = score; }
            public int Score { get; private set; } // readonly
        }

        private int _timerDelay;
        private int _score;
        private readonly SpriteBatch _sprite;
        private readonly Texture2D _texture2D;

        private const int MaxTimerDelay = 50;
        private const int MaxWiegth = 480;
        private const int MaxHeigth = 800;
        private const int PictureSize = 100;

        private Vector2 _position;

        public TargetBtn(SpriteBatch spriteBatch,Texture2D texture2D)
        {
            var r = new Random();
            _timerDelay = r.Next(MaxTimerDelay);
            _position = new Vector2(r.Next(MaxWiegth - PictureSize), r.Next(MaxHeigth - PictureSize));
            _sprite = spriteBatch;
            _texture2D = texture2D;
            _score = 999;
        }
        
        public void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            
            
            _score -= 9;
            if (_score <= 0) RaiseSampleEvent();
        }

        public void OnTap(object sender, GestureEventArgs e)
        {
            var x = e.GetPosition((UIElement) sender).X;
            var y = e.GetPosition((UIElement)sender).Y;
            if (_position.X+PictureSize>=x && _position.X<=x
                &&_position.Y+PictureSize>=y && _position.Y<=y
                ) RaiseSampleEvent();
        }

        public void OnDraw(object sender, GameTimerEventArgs e)
        {
            if (_timerDelay-- > 0) return;
            _sprite.Begin();
            _sprite.Draw(_texture2D, _position, Color.Wheat );
            _sprite.End();
            
            // TODO: Add your drawing code here
        }

        // Declare the delegate (if using non-generic pattern).
        public delegate void FinishEventHandler(object sender, FinishEventArgs e);

        // Declare the event.
        public event FinishEventHandler FinishEvent;

        // Wrap the event in a protected virtual method
        // to enable derived classes to raise the event.
        protected virtual void RaiseSampleEvent()
        {
            // Raise the event by using the () operator.
            if (FinishEvent != null)
                FinishEvent(this, new FinishEventArgs(_score));
        }


    }
}
